<template>
  <Dialog :visible="editDialogVisible" @close="hangleCloseEditDialog" title="编辑活动" :destroy-on-close="true" width="50%">
    <el-form :model="editForm" :rules="rules" label-position="top" ref="formRef" class="myform">
      <div class="input-group">
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model="editForm.activityName"></el-input>
        </el-form-item>

        <el-form-item label="举办社团" prop="organization">
          <el-select v-model="editForm.organization" placeholder="请选择举办社团">
            <OrganizationOption></OrganizationOption>
          </el-select>
        </el-form-item>
      </div>

      <div class="input-group">
        <el-form-item label="活动时间" prop="activityTime">
          <el-date-picker v-model="editForm.activityTime" value-format="YYYY-MM-DD" type="date" placeholder="请选择活动时间" />
        </el-form-item>
      </div>

      <el-form-item label="活动简介" prop="activityIntro">
        <el-input type="textarea" v-model="editForm.activityIntro"></el-input>
      </el-form-item>

      <div class="upload-group">
        <el-form-item label="活动照片" prop="photos">
          <el-scrollbar max-height="240px">
            <Upload :fileList="editForm.photos" @change="handlePhotoChange" @delete="handlePhotoDelete">
            </Upload>
          </el-scrollbar>
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="hangleCloseEditDialog">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
  import {
    reactive,
    ref
  } from "vue";
  import {
    ElMessage,
    UploadFile,
    UploadFiles,
    FormInstance,
    FormRules
} from "element-plus";
import { throttle } from "lodash";

  import Upload from "./Upload.vue";
  import OrganizationOption from "@/components/common/OrganizationOption.vue";
  import Dialog from '@/components/common/Dialog.vue';

  import {
    options
  } from "@/data/select.ts";

  import {
    updateActivity
  } from "@/api/activity/index.ts";
  import {
    deletePics,
    uploadPic
  } from "@/api/picture/index.ts";

  const props = defineProps(["editDialogVisible", "editForm"]);
  const emits = defineEmits(["closeEditDialog", "confirm"]);

  const formRef = ref < FormInstance > ()

  const rules = reactive < FormRules > ({
    activityName: [{
      required: true,
      message: '请输入活动名称',
      trigger: 'change',
    }],
    organization: [{
      required: true,
      message: '请选择举办社团',
      trigger: 'change',
    }],
    activityTime: [{
      required: true,
      message: '请选择活动时间',
      trigger: 'change',
    }],
    activityIntro: [{
      required: true,
      message: '请输入活动简介',
      trigger: 'input',
    }],
  });


  // 活动内容

  const handlePhotoChange = (files: UploadFiles, file ? : UploadFile) => {
    props.editForm.photos = files as never;
    props.editForm.addPhotos.push(file);
  };

const handlePhotoDelete = (file: IObj) => {
    if (file.picId) {
      props.editForm.deleteIds.push(file.picId);
    }

    props.editForm.photos =
      props.editForm.photos.filter(
        (item: UploadFile) => item.uid != file.uid
      );

    props.editForm.addPhotos = props.editForm.addPhotos.filter(
      (item: UploadFile) => item.uid != file.uid
    );
  };

  const hangleCloseEditDialog = () => {
    emits("closeEditDialog");
};

const update = async () => {
  let flag = false;

  const { data: res1 } = await updateActivity({
    _id: props.editForm.rowId,
    name: props.editForm.activityName,
    intro: props.editForm.activityIntro,
    time: props.editForm.activityTime,
    organization: props.editForm.organization,
  });

  if (res1.code !== 200) {
    flag = true;
  }

  if (props.editForm.deleteIds.length > 0) {
    const { data: res2 } = await deletePics(props.editForm.rowId.toString(), props.editForm.deleteIds);

    if (res2.code !== 200) {
      flag = true;
    }
  }

  const formData = getFormData(props.editForm.addPhotos);

  if (props.editForm.addPhotos.length > 0) {
    const {
      data: res3
    } = await uploadPic(props.editForm.rowId.toString(), formData);

    if (res3.code !== 200) {
      flag = true;
    }
  }

  if (!flag) {
    emits("confirm");
  }
};

const handleConfirm = throttle(async () => {
  // console.log(props.editForm.addPhotos);
  // console.log(props.editForm.addSceneFiles);
  if (formRef.value) {
    await (formRef.value as FormInstance).validate(async (valid: boolean, fields) => {
      if (valid) {
        hangleCloseEditDialog();
        update();
      } else {
        console.log(fields);
      }
    })
  }
}, 2000);

function getFormData(files: IObj[]) {
    let formData = new FormData();

    files.forEach((file: IObj) => {
      formData.append("photo", file.raw as Blob);
    });

    return formData;
}
</script>

<style lang="less" scoped>
  .myform {
    padding: 0 20px;

    :deep(.el-select) {
      width: 100%;
    }

    :deep(.el-textarea__inner) {
      height: 100px;
      resize: none;
    }

    .input-group {
      width: 100%;
      display: flex;
      justify-content: space-between;

      :deep(.el-form-item) {
        width: 44%;
        margin-bottom: 12px;
      }
    }

    .upload-group {
      width: 100%;
      display: flex;
      justify-content: space-between;

      :deep(.el-form-item) {
        // width: 44%;
        // max-height: 240px;
        margin-bottom: 12px;
      }
    }
  }
</style>